
const express = require('express');
const router = express.Router();
const OrderModel = require('../db/OrderModel');
const PatientModel = require('../db/PatientModel');//患者信息表
const moment = require('moment');
const UserModel = require('../db/UserModel');//人员表
const CmmuseumModel = require('../db/CmmuseumModel');//门店表
const DepartmentModel = require('../db/DepartmentModel');//科室表
const RegistrationinformationModel = require('../db/RegistrationinforMation');
const now = () => {
    return moment().format('YYYY-MM-DD HH:mm:ss')
}
const fun = require('../middlewares/Fun');

/**
 * 订单模型
 * 订单crud
 */
//生成订单号
function setOrderNumber() {
    return new Promise((resolve, reject) => {
        const orderId = moment().format('YYYYMMDD') + parseInt(Math.random() * 900000 + 100000);
        OrderModel.findOne({ orderid: orderId }).then(result => {
            if (result) {
                return resolve(this.setOrderNumber());
            }
            resolve(orderId);
        }).catch(err => {
            reject(err);
        });
    });
}


//创建订单
router.post('/save', function (req, res) {
    let { doctor, consumptionmoney, consumptiontime, payer, ordertype, paytype } = req.body;
    if (!doctor || !consumptionmoney || !consumptiontime || !payer || !ordertype || !paytype) {
        return res.json({
            code: 201,
            mes: '参数错误。'
        });
    }
    setOrderNumber().then(orderid => {
        let obj = {};
        OrderModel.findOne({ orderid: orderid }).then(order => {
            if (!order) {
                req.body.orderid = orderid;
                if (req.body.chargeschedule) {
                    req.body.chargeschedule = JSON.parse(req.body.chargeschedule)
                }
                if (!req.body.paytime) {
                    req.body.paytime = now();
                }
                const temp = new OrderModel(req.body);
                obj.receptiontime = req.body.consumptiontime;
                obj.receptionstate = 1;//接诊状态
                obj.receptiontype = 0;
                obj.registerpeople = req.body.doctor;
                obj.registrationlv = 0;
                obj.registrationmoney = Math.abs(req.body.consumptionmoney);
                obj.paystate = 1;//支付状态
                obj.payer = req.body.payer;
                DepartmentModel.findOne({ _id: req.body.department }, ['name']).then(department => {
                    obj.department = { id: req.body.department, department_name: department.name };//科室名称
                    return UserModel.findOne({ _id: req.body.doctor }, ['name']).then(user => {
                        obj.doctor = { id: req.body.doctor, doctor_name: user.name };//医生名称
                        return temp.save().then(docs => {
                            obj.orderid = docs.id;
                            const tempregistrationinfor = new RegistrationinformationModel(obj);
                            if (req.body.ordertype.indexOf('挂号费') > -1) {//判断是否为挂号订单
                                //添加挂号信息
                                return tempregistrationinfor.save().then(tempregis => {
                                    return PatientModel.update({ _id: req.body.payer }, { $set: { status: 2 } }).then(p => {
                                        return res.json({
                                            code: 200,
                                            mes: '创建订单成功.',
                                            docs
                                        });
                                    })
                                })
                            } else {
                                return RegistrationinformationModel.update({ orderid: req.body.regisid }, { $set: { 'cureorder': { id: docs._id.toString(), state: docs.paystate } } }).then(t => {
                                    return res.json({
                                        code: 200,
                                        mes: '创建订单成功.',
                                        docs
                                    });
                                })
                            }
                        })
                    })


                }).catch(err => {
                    return res.json({
                        code: 201,
                        mes: '创建订单失败.'
                    });
                })

            } else {
                return res.json({
                    code: 202,
                    mes: '此订单已存在!'
                });
            }
        })
    }).catch((err) => {
        return res.json({
            err,
            code: 203,
            mes: '发生意外错误。'
        });
    })
});

router.get('/remove', (req, res) => {
    let id = req.query.id;
    // OrderModel.findOne({ _id: id }).then(result => {
    //     result.orderstate = false;
    //     return result.save().then(data => {
    //         return res.json({
    //             result,
    //             code: 200,
    //             mes: '删除成功。'
    //         });
    //     })
    // }).catch(err => {
    //     return res.json({
    //         err,
    //         code: 201,
    //         mes: '发生意外错误。'
    //     });
    // })
    OrderModel.update({ _id: id }, { orderstate: false }).then(result => {
        console.log(result)
        return res.json({
            code: 200,
            mes: '删除成功。'
        });
    }).catch(() => {
        return res.json({
            code: 201,
            mes: '删除失败。'
        });
    })
});
//设置订单表中的医生，科室，中医馆，客户ID为对应姓名或名称
function setidname(data, orderarr) {
    let tempobj = {};
    try {
        for (let i = 0; i < data[0].length; i++) {
            tempobj[data[0][i]._id] = data[0][i];
        }
        for (let i = 0; i < data[1].length; i++) {
            tempobj[data[1][i]._id] = data[1][i];
        }
        for (let i = 0; i < data[2].length; i++) {
            tempobj[data[2][i]._id] = data[2][i];
        }
        for (let i = 0; i < data[3].length; i++) {
            tempobj[data[3][i]._id] = data[3][i];
        }
        for (let i = 0; i < orderarr.length; i++) {
            orderarr[i].payer_name = tempobj[orderarr[i].payer].username;
            orderarr[i].doctor_name = tempobj[orderarr[i].doctor].name;
            orderarr[i].clinicname_name = tempobj[orderarr[i].clinicname].name;
            orderarr[i].department_name = tempobj[orderarr[i].department].name;
        }
    } catch (error) {
        console.log(error, 666)
    }

    return orderarr;
}
//收费、订单列表
router.get('/find', (req, res) => {
    let pageindex = req.query.pageindex || 1;//页码
    let pagesize = req.query.pagesize || 9;//每页显示数据条数 
    let state = req.query.state;//   支付状态 1:待收费    2:已收费   3:已退费
    let starttime = req.query.starttime;
    let endtime = req.query.endtime;
    let searchtxt = req.query.searchtxt;
    const patient = PatientModel.find({}, ['username']);
    const doctor = UserModel.find({}, ['name']);
    const cmmuseum = CmmuseumModel.find({}, ['name']);
    const department = DepartmentModel.find({}, ['name']);
    let orderarr = [];
    let count = '';
    if (!state) {
        return res.json({
            code: 202,
            mes: '参数错误。'
        });
    }
    //开始组合条件
    let query = {};
    query.paystate = state;
    if (req.query.starttime && req.query.endtime && state != 3) {
        starttime = moment(new Date(starttime)).format('YYYY-MM-DD 00:00');
        endtime = moment(new Date(endtime)).format('YYYY-MM-DD 23:59');
        query.paytime = { $gte: starttime, $lte: endtime };
    } else if (req.query.starttime && req.query.endtime && state == 3) {
        starttime = moment(new Date(starttime)).format('YYYY-MM-DD 00:00');
        endtime = moment(new Date(endtime)).format('YYYY-MM-DD 23:59');
        query.refundtime = { $gte: starttime, $lte: endtime };
    }
    if (!searchtxt && starttime && endtime) {
        OrderModel.count(query).then(counts => {
            return OrderModel.find(query).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).lean(true).then(order => {
                orderarr = order;
                count = counts;
                return Promise.all([patient, doctor, cmmuseum, department]);
            }).then(data => {
                orderarr = setidname(data, orderarr);
                return res.json({
                    code: 200,
                    mes: '查询订单成功。',
                    data: orderarr,
                    count: count
                });
            }).catch(() => {
                return res.json({
                    code: 201,
                    mes: '查询订单失败。',
                    err
                });
            })
        }).catch((err) => {
            return res.json({
                code: 201,
                mes: '查询订单失败。'
            });
        })

    } else if (searchtxt && !starttime || searchtxt && starttime) {
        const reg = new RegExp(searchtxt, 'i');//模式正则
        PatientModel.find({ $or: [{ username: { $regex: reg } }, { userphone: { $regex: reg } }] }, ['_id']).then(pt => {
            let ptarr = [];
            for (let i = 0; i < pt.length; i++) {
                ptarr.push(pt[i].id);
            }
            query.payer = { $in: ptarr };
            return OrderModel.count(query).then(counts => {
                if (counts > 0) {
                    return OrderModel.find(query).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).lean(true).then(order => {//根据患者姓名查询
                        orderarr = order;
                        return Promise.all([patient, doctor, cmmuseum, department]);
                    }).then(data => {
                        orderarr = setidname(data, orderarr);
                        return res.json({
                            code: 200,
                            mes: '查询订单成功。',
                            data: orderarr,
                            count: counts
                        });
                    })
                } else {
                    return res.json({
                        code: 200,
                        mes: '查询订单成功。',
                        data: orderarr,
                        count: counts
                    });
                }

            }).catch((err) => {
                return res.json({
                    code: 201,
                    mes: '查询订单失败。'
                });
            })
        })
    } else {
        OrderModel.count(query).then(counts => {
            count = counts;
            return Promise.all([patient, doctor, cmmuseum, department]);
        }).then(data => {
            return OrderModel.find(query).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).lean(true).then(order => {
                orderarr = setidname(data, order);
                return res.json({
                    code: 200,
                    mes: '查询订单成功。',
                    data: orderarr,
                    count: count
                });
            })
        }).catch((err) => {
            return res.json({
                code: 201,
                mes: '查询订单失败。',
                data: err
            });
        })
    }
});

router.get('/findone', (req, res) => {
    let id = req.query.id;
    if (!id) {
        return res.json({
            code: 201,
            mes: '缺少参数。'
        });
    }
    let orderarr = [];
    OrderModel.findOne({ _id: id, orderstate: true }).lean(true).then(order => {
        orderarr = order;
        return Promise.all([PatientModel.find({ _id: order.payer }, ['username']), UserModel.find({ _id: order.doctor }, ['name']), CmmuseumModel.find({ _id: order.clinicname }, ['name']), DepartmentModel.find({ _id: order.department }, ['name'])]);
    }).then(data => {
        let tempobj = {};
        tempobj[data[0][0]._id] = data[0][0];
        tempobj[data[1][0]._id] = data[1][0];
        tempobj[data[2][0]._id] = data[2][0];
        tempobj[data[3][0]._id] = data[3][0];
        orderarr.payer_name = tempobj[orderarr.payer].username;
        orderarr.doctor_name = tempobj[orderarr.doctor].name;
        orderarr.clinicname_name = tempobj[orderarr.clinicname].name;
        orderarr.department_name = tempobj[orderarr.department].name;

        return res.json({
            code: 200,
            mes: '查询成功。',
            data: orderarr
        });
    }).catch((err) => {
        return res.json({
            err,
            code: 202,
            mes: '意外错误。'
        });
    })
});

//修改订单状态
router.post('/update', function (req, res) {
    const _id = req.body.id;
    const update = JSON.parse(req.body.data);
    let paystate = update.paystate;
    if (!_id) {
        return res.json({
            code: 201,
            mes: "缺少参数!"
        })
    }
    OrderModel.findById(_id).then(user => {
        if (user) {
            return OrderModel.update({ _id }, { $set: update }).then(docs => {
                if (user.ordertype.indexOf('挂号费') > -1) {
                    //修改挂号单信息
                    return RegistrationinformationModel.update({ orderid: _id }, { $set: { receptionstate: 2, paystate: paystate } }).then(a => {
                        return res.json({
                            code: 200,
                            mes: '修改成功.'
                        });
                    });
                } else {
                    RegistrationinformationModel.update({ 'cureorder.id': _id }, { $set: { 'cureorder': { id: _id.toString(), state: paystate } } }).then(() => {
                        return res.json({
                            code: 200,
                            mes: '修改成功.'
                        });
                    })
                }
            }).catch(err => {
                return res.json({
                    code: 201,
                    mes: '修改失败.'
                });
            })
        } else {
            return res.json({
                code: 202,
                mes: '此ID不存在.'
            });
        }
    }).catch(err => {
        return res.json({
            code: 203,
            mes: '数据库错误,请稍后重试.'
        });
    })
});

//退款
router.post('/reimburse', (req, res) => {
    let id = req.body.id;
    let money = req.body.money;//退费总金额
    let operator = req.body.operator;//操作人
    let ordertype = req.body.ordertype;//订单类型  例：挂号费
    let arr;
    try {
        arr = JSON.parse(req.body.arr);//退费项目名称数组
        if (arr.length <= 0) {
            return res.json({
                code: 201,
                mes: "缺少退费项目."
            })
        }
    } catch (error) {
        return res.json({
            code: 201,
            mes: "参数格式错误."
        })
    }
    if (!id || !money || !operator || !arr) {
        return res.json({
            code: 201,
            mes: "缺少必要参数."
        })
    }
    OrderModel.update({ _id: id }, { $set: { 'refundtime': now(), 'refundmoney': money, 'refundoperator': operator } }).then(tempup => {
        if (tempup.n > 0) {
            //退款操作：修改退费明细数组中，每个退费的项目
            OrderModel.findById(id).then(order => {
                let p_arr = [];
                let num = 0;
                p_arr = order.chargeschedule;
                for (let i = 0; i < p_arr.length; i++) {//循环每一条明细，判断是否是退费项目
                    if (arr.indexOf(p_arr[i].p_name) > -1) {//判断此订单的收费明细是否包含传进来的退费项目
                        p_arr[i].p_refundstate = true;
                        p_arr[i].p_paystate = 3;
                    }
                    if (p_arr[i].p_paystate == 3) {
                        num++;
                    }
                }

                if (p_arr.length == arr.length) {
                    //判断订单类型，以此确定修改挂号单中的支付状态
                    if (ordertype.indexOf('挂号') < 0) {//判断退的是否为挂号费，不是则执行if
                        return OrderModel.update({ _id: id }, { $set: { paystate: 3, chargeschedule: p_arr } }).then(parameter => {
                            return RegistrationinformationModel.update({ 'cureorder.id': id }, { $set: { 'cureorder.id': id, 'cureorder.state': 3 } }).then(r => {
                                return res.json({
                                    mes: '退款操作成功。',
                                    code: 200
                                });
                            })
                        })
                    } else {
                        return OrderModel.update({ _id: id }, { $set: { paystate: 3, chargeschedule: p_arr } }).then(parameter => {
                            return res.json({
                                mes: '退款操作成功。',
                                code: 200
                            });
                        })
                    }
                } else {//订单分多次退费
                    if (num != p_arr.length) {
                        return OrderModel.update({ _id: id }, { $set: { chargeschedule: p_arr } }).then(parameter => {
                            return res.json({
                                mes: '退款操作成功。',
                                code: 200
                            });
                        })
                    } else {//订单项目已退完的情况
                        return OrderModel.update({ _id: id }, { $set: { paystate: 3, chargeschedule: p_arr } }).then(parameter => {
                            return RegistrationinformationModel.update({ 'cureorder.id': id }, { $set: { 'cureorder.id': id, 'cureorder.state': 3 } }).then(r => {
                                return res.json({
                                    mes: '退款操作成功。',
                                    code: 200
                                });
                            })
                        })
                    }

                }

            }).catch(() => {
                return res.json({
                    code: 202,
                    mes: '退款操作失败。'
                });
            })
        }
        else {
            return res.json({
                code: 202,
                mes: '退款操作失败。'
            });
        }
    }).catch(() => {
        return res.json({
            code: 201,
            mes: '意外错误。'
        });
    })


});

//取消支付
router.get('/cancelPay/:id', function (req, res) {
    const _id = req.params.id;
    if (!_id) {
        return res.json({
            code: 201,
            mes: "缺少参数!"
        })
    }
    OrderModel.findById(_id).then(user => {
        if (user) {
            return OrderModel.update({ _id }, { $set: { orderstate: false } }).then(docs => {
                return res.json({
                    code: 200,
                    mes: '修改成功.'
                });
            })
        } else {
            return res.json({
                code: 202,
                mes: '此ID不存在.'
            });
        }

    }).catch(err => {
        return res.json({
            code: 203,
            mes: '数据库错误,请稍后重试.'
        });
    })
});
//患者消费信息
router.get("/onsumerinforMation", (req, res) => {
    let id = req.query.id;
    let pageindex = req.query.pageindex || 1;//页码
    let pagesize = req.query.pagesize || 9;//每页显示数据条数 
    let consts;
    if (!id) {
        return res.json({
            code: 201,
            mes: "缺少参数!"
        })
    };
    OrderModel.count({ payer: id }).then(constss => {
        consts = constss
        return OrderModel.find({ payer: id, $or: [{ paystate: 2 }, { paystate: 3 }] }).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).lean(true).then(data => {
            return Promise.all(data.map(values => {
                return CmmuseumModel.find({ _id: values.clinicname }, { name: 1 }).then(name => {
                    values.clinicname = name[0].name;
                    return values
                })
            }))
        })
    }).then(data => {
        console.log(data, 999)
        let totalaMount = 0;
        let refundmoney = 0;
        for (let a = 0; a < data.length; a++) {
            for (let b = 0; b < data[a].chargeschedule.length; b++) {
                totalaMount += data[a].chargeschedule[b].p_money * 1
                if (data[a].chargeschedule[b].p_paystate == 3) {
                    refundmoney += data[a].chargeschedule[b].p_money * 1
                }
            }
        }
        return res.json({
            code: 200,
            mes: '查询成功.',
            data,
            consts,
            totalaMount,
            refundmoney
        });
    }).catch(err => {
        return res.json({
            code: 201,
            mes: '数据库错误,请稍后重试.',
            err
        });
    })
});

module.exports = router;    